require 'filesystem'
Utility = {}

---根据路径，获得绝对路径
---@param path string 相对于根文件夹(eg:script\main.lua)
function Utility.Get_absolute_path( path )
	return ('%s\\%s'):format(CURRENT_PATH, path)
end

---获得文件类型
function Utility.Get_filetype ( filename )
	for i = #filename, 1, -1 do
		if filename:sub(i, i) == '.' then
			return filename:sub(i+1), i+1
		end
	end
	return ''
end

---获得文件名称
function Utility.get_file_name( file_path )
	for i = #file_path, 1, -1 do
		if file_path:sub(i, i) == '\\' then
			return file_path:sub(i+1)
		end
	end
	return file_path
end

--获取相对路径
function Utility.get_file_relative_path( file_path, path )
	local _, _end = file_path:find( (path:gsub('-', [[%%-]])) )

	if _end then
		return file_path:sub(_end+1+1)
	else
		return file_path
	end
end

-- 点坐标关于直线对称
-- x1：当前位置
-- x2：直线位置
function Utility.point_vertical_symmetry(x1, x2)
	return 2*x2 - x1
end

-- 角度关于Y轴对称
function Utility.angle_y_vertical(angle)
    angle = angle%360
    
    if angle <= 180 then
        return 180 - angle
    else
        return 360 - (angle-180)
    end
end

-- 角度关于x轴对称
function Utility.angle_x_vertical(angle)
    angle = angle%360
    
	return 360-angle
end

-- 弧度关于Y轴对称
function Utility.radian_y_vertical(radian)
	return Utility.angle_y_vertical( radian * 180/math.pi ) * math.pi/180
end

-- 弧度关于x轴对称
function Utility.radian_x_vertical(radian)
	return Utility.angle_x_vertical( radian * 180/math.pi ) * math.pi/180
end


function Utility.is_lni_map( path )
	local s_path = ([[%s\.w3x]]):format(path)
	local path = fs.path(s_path)
	return fs.exists( path )
end

function io.load(file_path)
	local name 
	if type(file_path) == 'string' then 
		name = file_path 
	else 
		name = file_path:string()
	end 
	local f, e = io.open(name, "rb")
	if f then
		if f:read(3) ~= '\xEF\xBB\xBF' then
			f:seek('set')
		end
		local content = f:read 'a'
		f:close()
		return content
	else
		return false, e
	end
end

function io.save(file_path, content)
	local name 
	if type(file_path) == 'string' then 
		name = file_path 
	else 
		name = file_path:string()
	end 

	local f, e = io.open(name, "wb")
	if f then
		f:write(content)
		f:close()
		return true
	else
		return false, e
	end
end


function decodeURI(s)
    s = string.gsub(s, '%%(%x%x)', function(h) return string.char(tonumber(h, 16)) end)
    return s
end

function encodeURI(s)
    s = string.gsub(s, "([^%w%.%- ])", function(c) return string.format("%%%02X", string.byte(c)) end)
    return string.gsub(s, " ", "+")
end